/*****************************************************************
/     filename:   env.c
/
/  description:   Implements the UNIX env utility
/
/       author:   Szechy, Jared
/     login id:   cps444-n1.10
/
/        class:   CPS 444
/   instructor:   Perugini
/   assignment:   Homework #2
/
/     assigned:   September 9, 2009
/          due:   September 16, 2009
/
/***************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>

extern char** environ;

int main(int argc, char *argv[], const char *envp[])
{
   int optc, i;
   bool ignore_environ = false;

   opterr = 0;

   while ((optc = getopt(argc, argv, "i?")) != -1)
      switch (optc)
      {
         case 'i':
            ignore_environ = true;
            break;
         case '?':
            if (isprint(optopt))
               fprintf(stderr, "env: invalid option -- '%c'\n", optopt);
            else
               fprintf(stderr, "Unknown option character `\\x%x;.\n", optopt);
            return 1;
         default:
            abort();
      }

   if (ignore_environ)
   {
      static char *dummy_environ[] = { NULL };
      environ = dummy_environ;
   }
 
   while (optind < argc && strchr(argv[optind], '='))
      putenv(argv[optind++]);

   if (argc <= optind)
   {
      char *const *e = environ;
      while (*e)
         puts(*e++);
      exit(0);
   }

   execvp(argv[optind], &argv[optind]);

   return 0;
}
